<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleCateChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <!-- tab-click 点击时,会将tab-pane标签name属性赋值给activeName -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数按钮 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="!isBtnDisable"
            @click="addParamsVisible = true"
            >动态参数</el-button
          >
          <!-- 动态参数table -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon--edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delEditDialogMes(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性按钮 -->
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="!isBtnDisable"
            @click="addParamsVisible = true"
            >静态参数</el-button
          >
          <!-- 静态参数table -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag -->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon--edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delEditDialogMes(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 动态参数 表单 -->
    <!-- title 计算属性动态绑定该值 -->
    <el-dialog
      :title="titleText"
      @close="closeParamsParams"
      :visible.sync="addParamsVisible"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="forParamsFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑dialog -->
    <el-dialog
      title="修改"
      @close="closeEditParams"
      :visible.sync="editParamsVisible"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="forEditFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [], // 也是级联选择框 options属性绑定的数据源
      cascaderProps: {
        //配置级联选择框
        value: 'cat_id', // 选择的属性
        label: 'cat_name', // 界面展示的属性
        children: 'children',
        // 次级菜单的展开方式
        expandTrigger: 'hover',
      },
      selectedCateKeys: [], // 级联选择框双向绑定的数组
      activeName: 'many', // el-tab 默认的页签name
      manyTableData: [], // 动态参数数据
      onlyTableData: [], // 静态参数数据
      addParamsVisible: false, //是否显示参数表单dialog
      addParamsForm: {
        // 参数表单 el-form 绑定的对象
        attr_name: '',
      },
      addParamsFormRules: {
        // 表单的验证规则对象
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      editParamsVisible: false, // 是否显示修改dialog
      editParamsForm: {
        attr_name: '',
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      curManyTableData: [],
      curOnlyTableData: [],
    }
  },
  async created() {
    // 获取所有的商品分类
    const { data: res } = await this.$http.get('categories', {
      params: {
        type: 3,
      },
    })
    if (res.meta.status !== 200) {
      return this.$http.error('获取商品分类数据失败')
    }
    this.cateList = res.data.result // 商品分类数据
  },
  methods: {
    handleCateChange() {
      this.getParamsDate()
    },
    handleTabClick() {
      // tab页签切换
      console.log(this.activeName)
      this.getParamsDate()
    },
    async getParamsDate() {
      console.log(this.selectedCateKeys)
      if (this.selectedCateKeys.length != 3) {
        // 表示选中的不是三级分类，v-model 可直接将数组清空
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return
      }
      // 根据所选分类的id , 和当前分类的面板
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      if (res.meta.status !== 200) this.$message.error('获取参数失败')
      this.$message.success('获取参数成功')
      // 判断数据是 静态参数还是静态参数数据，进行赋值
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加属性 控制文本框显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },

    // 动态参数表单事件
    // 关闭dialog
    closeParamsParams() {
      this.$refs.forParamsFormRef.resetFields()
    },

    // 点击按钮添加参数
    addParams() {
      var _this = this
      this.$refs.forParamsFormRef.validate((valid) => {
        if (!valid) return
        if (_this.activeName === 'many') {
          _this.manyTableData.push({
            attr_name: _this.addParamsForm.attr_name,
          })
        } else {
          _this.onlyTableData.push({
            attr_name: _this.addParamsForm.attr_name,
          })
        }
        _this.$message.success('添加成功---数据库未做关联')
        _this.addParamsVisible = false
      })
    },

    // 点击编辑按钮事件
    showEditDialog(attr_id) {
      this.editParamsVisible = true
      if (this.activeName === 'many') {
        this.curManyTableData = this.manyTableData.find((item) => {
          return item.attr_id === attr_id
        })
        this.editParamsForm.attr_name = this.curManyTableData.attr_name
      } else {
        this.curOnlyTableData = this.onlyTableData.find((item) => {
          return item.attr_id === attr_id
        })
        this.editParamsForm.attr_name = this.curOnlyTableData.attr_name
      }
    },
    // 关闭dialog事件
    closeEditParams() {
      this.$refs.forEditFormRef.resetFields()
    },
    // 确认修改
    editParams() {
      var _this = this
      this.$refs.forEditFormRef.validate((valid) => {
        if (!valid) return
        _this.$message.success('修改成功---,数据库未做联动')
        console.log(_this.editParamsForm)
        if (_this.activeName === 'many') {
          _this.manyTableData.forEach((item) => {
            if (item.attr_id === _this.curManyTableData.attr_id) {
              item.attr_name = _this.editParamsForm.attr_name
            }
          })
        } else {
          _this.onlyTableData.forEach((item) => {
            if (item.attr_id === _this.curOnlyTableData.attr_id) {
              item.attr_name = _this.editParamsForm.attr_name
            }
          })
        }
      })
      this.editParamsVisible = false
    },
    // 删除操作
    async delEditDialogMes(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户点击了确认删除，则返回字符串'confirm'
      // 如果用户点击了取消删除，本应该会报错。但是我们进行了catch(err=>{return err}); 此时返回的'cancel'
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 请求后刷新数据
      if (this.activeName === 'many') {
        this.manyTableData = this.manyTableData.filter((item) => {
          return item.attr_id !== attr_id
        })
      } else {
        this.onlyTableData = this.onlyTableData.filter((item) => {
          return item.attr_id !== attr_idd
        })
      }
      this.$message.success('删除成功，数据库未做关联')
    },

    // 文本框数去焦点或者 按下enterl 都会触发
    handleInputConfirm() {
      console.log('ok')
    },

    // showInput 点击事件
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获取对象
      // $nextTick 方法作用：当页面上元素重新渲染之后，才会指定回调函数代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row){
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputValue = ''
      row.inputVisible = false;
      // 需要发起请求保持到数据库中
    },
    async handleClose(i, row){
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户点击了确认删除，则返回字符串'confirm'
      // 如果用户点击了取消删除，本应该会报错。但是我们进行了catch(err=>{return err}); 此时返回的'cancel'
      if (confirmResult === 'confirm') {
        row.attr_vals.splice(i, 1);
        this.$message.info('数据库未做联动');
      }
      return;
    }
  },
  computed: {
    // 如果按钮需要被禁用 返回true 否则返回false
    isBtnDisable() {
      // if (this.selectedCateKeys.length !== 3) {
      //   return true
      // }
      return false
      // return false
    },
    // 当前选中的三级分类的id
    cateID() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },

    // 计算属性动态绑定该值
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>